<?php

namespace App\Console\Commands;

use App\Models\Order;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class OrderUseExpired extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:use-expired';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '处理过期未使用的订单';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('开始检查过期订单...');

        $expiredOrders = Order::query()
            ->where('state', Order::STATE_WAIT_USE)
            ->whereIn('sell_type', [Order::SELL_CAMP, Order::SELL_LEASE, Order::SELL_COMBO])
            ->where('sell_json->end_time', '<=', date('Y-m-d H:i:s'))
            ->get();

        $count = $expiredOrders->count();

        if ($count === 0) {
            $this->info('没有需要处理的过期订单');
            return;
        }

        $this->info("发现 {$count} 个过期订单，正在处理...");

        $successCount = 0;
        $failedCount = 0;

        foreach ($expiredOrders as $order) {
            try {
                $order->state = Order::STATE_USE_EXPIRE;
                $order->save();
                $successCount++;

                // 这里可以添加其他业务逻辑，如发送通知等
                Log::info("订单 {$order->order_sn} 已标记为过期");

            } catch (\Exception $e) {
                $failedCount++;
                Log::error("处理过期订单 {$order->order_sn} 失败: " . $e->getMessage());
            }
        }

        $this->info("处理完成！成功: {$successCount}, 失败: {$failedCount}");
    }
}
